// pages/new_address/new_address.js
const getToken= require('../../utils/get_token.js');
var feedbackApi= require('../common/showToast.js');
let memberId, animation;
let pIndex=0,cIndex=0,rIndex=0;
let cookie, token;
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    goodShopsn(that);
  } else {
    let tokens = await getToken.getToken();
    goodShopsn(that);
  }
}
const goodShopsn = (that) => {//省
  let params = [ 'common/area/selectParentList', {}]
  getToken.getData(function (res) {
    console.log(res.data)
    //res.data.datas = JSON.parse(res.data.datas)
    that.setData({
      provinces: res.data.datas
    })
  }, ...params)
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
		address:'选择地区',
		animationAddressMenu: {},
		addressMenuIsShow: false,
		provinces: [],
		citys: [],
    regions:[],
		mobile:'',
		addressId:'',
    province: '',
		city:'',
    region:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		var that = this;
		memberId = wx.getStorageSync('memberId');
		that.data.mobile = wx.getStorageSync('mobile');
    cookie = wx.getStorageSync('cookie') || '';
    token = wx.getStorageSync('token') || '';
     pIndex = 0;
     cIndex = 0;
     rIndex = 0;
		that.setData({
			mobile: that.data.mobile
		})
		// 初始化动画变量
		var animation = wx.createAnimation({
			duration: 500,
			transformOrigin: "50% 50%",
			timingFunction: 'ease',
		})
		this.animation = animation;
		// 默认联动显示北京
    ckToken(that);
  },
  
	selectDistrict: function (e) {//点击
		var that = this
		// 如果已经显示，不在执行显示动画
		if (that.data.addressMenuIsShow) {
			return
		}
		// 执行显示动画
		that.startAddressAnimation(true)
	},
	// 执行动画
	startAddressAnimation: function (isShow) {
		var that = this
		if (isShow) {
			// vh是用来表示尺寸的单位，高度全屏是100vh
			that.animation.translateY(0 + 'vh').step()
		} else {
			that.animation.translateY(45 + 'vh').step()
		}
		that.setData({
			animationAddressMenu: that.animation.export(),
			addressMenuIsShow: isShow,
		})
	},
	// 点击地区选择取消按钮
	cityCancel: function (e) {
		this.startAddressAnimation(false)
	},
	// 点击蒙版时取消组件的显示
	hideCitySelected: function (e) {
		this.startAddressAnimation(false)
	},
	// 点击地区选择确定按钮
	citySure: function (e) {
		var that = this
		that.startAddressAnimation(false)
		// 将选择的城市信息显示到输入框
    var address = that.data.province + that.data.city + that.data.region;
		console.log(address)
		if (address=="")
		{
			address ='选择地区'
		}
		that.setData({
			address: address,
		})
	},
	bindchange:function(e){
		let that=this;
    if (pIndex != e.detail.value[0])//第一级动了省区
		{
      that.setData({
        citys:[],
        city:'',
        regions:[],
        region:''
      })
      pIndex = e.detail.value[0];
      cIndex = 0;
      rIndex = 0;
      that.data.province = that.data.provinces[pIndex].name;
      let params = ['common/area/selectChildrenList', {"parentId":that.data.provinces[pIndex].id}]
      getToken.getData(function (res) {
        //res.data.obj = JSON.parse(res.data.obj);
        if (res.data.obj.length > 0) {
          that.setData({
            citys: res.data.obj,
            addressId: res.data.obj[cIndex].id
          })
          that.data.city = that.data.citys[cIndex].name;
        }
      }, ...params)
    } else if (cIndex != e.detail.value[1]) {//第二级改变市区
        that.setData({
          regions: [],
          region:''
        })
      cIndex = e.detail.value[1];
      rIndex = 0;
      that.data.city = that.data.citys[cIndex].name;
      let params = [ 'common/area/selectChildrenList', {"parentId":that.data.citys[cIndex].id}]
      getToken.getData(function (res) {
       // res.data.obj = JSON.parse(res.data.obj);
        if (res.data.obj.length > 0) {
          that.setData({
            regions: res.data.obj,
            addressId: res.data.obj[rIndex].id
          })
          that.data.region = that.data.regions[rIndex].name;
        }
      }, ...params)
    } else if (rIndex != e.detail.value[2])//改变地区
    {
      rIndex = e.detail.value[2];
      if (that.data.regions.length>0)
      {
        that.data.region = that.data.regions[rIndex].name;
        that.setData({
          addressId: that.data.regions[rIndex].id
        })
      }
    }
	},
	formSubmit:function(e){//提交
	var that=this;
	var test = /^1(3|4|5|7|8)\d{9}$/;
	var val = e.detail.value;
    // val.name = encodeURIComponent(val.name);
    // val.addressD = encodeURIComponent(val.addressD);
  console.log(val)
    if(val.name==''){
			 feedbackApi.showToast({ title: '请输入姓名', mask: false })//调用 showToast
			 return false;
		}
		if (val.phone == '') {
			feedbackApi.showToast({ title: '请输入手机号码', mask: false })//调用 showToast
			return false;
		}
		if (!val.phone.match(test)) {
			feedbackApi.showToast({ title: '手机号格式不正确', mask: false })//调用 showToast
			return false;
		}
		if (val.address == '') {
			feedbackApi.showToast({ title: '请选择地区', mask: false })//调用 showToast
			return false;
		}
		if (val.addressD == '') {
			feedbackApi.showToast({ title: '请填写详细地址', mask: false })//调用 showToast
			return false;
		}
    let params = [ 'common/receiver/save', {"memberId": memberId,"name": val.name,"mobile":val.phone,"zipCode":"1234","areaStore": val.address,"address": val.addressD,"isDefault":val.isBool}]
    getToken.getData(function (res) {
      console.log(res.data)
     // res.data.flag = JSON.parse(res.data.flag);
      if (res.data.flag) {
        wx.navigateBack({
          delta: 1
        })
      } else {
        feedbackApi.showToast({ title: res.data.message, mask: false })//调用 showToast
      }
    }, ...params)	
	}
})